package org.csu.xzypetstore.controller;

import org.csu.xzypetstore.domain.Category;
import org.csu.xzypetstore.domain.Item;
import org.csu.xzypetstore.domain.Product;
import org.csu.xzypetstore.service.CatalogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/category")
@SessionAttributes({"productList","category","itemList","product"})
public class CategoryController {

    @Autowired
    private CatalogService catalogService;

    @GetMapping("/main")
    public String Main() {
        return "catalog/main";
    }


    @GetMapping("/ViewCategory")
    public String ViewProduct(String categoryId, Model model) {
        Category category = catalogService.getCategory(categoryId);
        List<Product> productList = catalogService.getProductListByCategory(categoryId);
        System.out.println(productList.size());
        model.addAttribute("productList", productList);
        model.addAttribute("category", category);
        return "catalog/category";
    }

    @GetMapping("/viewProduct")
    public String viewProduct(String productId, Model model) {
        if (productId != null) {
            List<Item> itemList11 = catalogService.getItemListByProduct(productId);
            List<Item> itemList = new ArrayList<Item>();
            for (int i=0;i<itemList11.size();i++)
            {
                Item item = catalogService.getItem(itemList11.get(i).getItemId());
                itemList.add(item);
            }
            Product product = catalogService.getProduct(productId);
            model.addAttribute("product", product);
            model.addAttribute("itemList", itemList);
        }
        return "catalog/product";
    }

    @GetMapping("/viewItem")
    public String ViewItem(String itemId,Model model)
    {
        Item item = catalogService.getItem(itemId);
        Product product = item.getProduct();
        processProductDescription(product);
        model.addAttribute("item",item);
        model.addAttribute("product",product);
        return "catalog/item";
    }

    private void processProductDescription(Product product){
        String [] temp = product.getDescription().split("\"");
        product.setDescriptionImage(temp[1]);
        product.setDescriptionText(temp[2].substring(1));
    }
    private void processProductDescription(List<Product> productList){
        for(Product product : productList) {
            processProductDescription(product);
        }
    }

}
